<?php

namespace App\Http\Resources\Counter;

use App\Enums\TradeStatus;
use App\Models\OrderItem;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class TableListResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        $data = parent::toArray($request);
        $finishDate = date('Y-m-d H:i:s');
        if (!empty($this->tableOrder)) {
            $data['total_money'] = round($this->tableOrder->getTotalMoney($finishDate), 2);
            $data['total_minute'] = 0;
            $data['total_table_money'] = 0;
            $tableItem = $this->tableOrder->getTableItem();
            if (!empty($tableItem)) {
                $data['total_minute'] = round($tableItem->getTotalMinutes($finishDate), 0);
                $data['total_table_money'] = round($tableItem->getTotalMoney($finishDate), 2);
            }
        }
        else {
            $data['total_money'] = null;
        }

        //查询结开订单数量, 查询所有OrderItem table_id = $this->id 的，且其关联的Order的status=TradeStatus::PendingOpen的数量
        $data['pending_open_order_count'] = OrderItem::where('table_id', $this->id)
            ->whereHas('order', function ($query) {
                $query->where('status', TradeStatus::PendingOpen);
            })->count();

        $data['alert_date'] = $this->alert_date ? $this->alert_date->format('Y-m-d H:i:s') : null;

        return $data;
    }
}
